package com.shlh.saas.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 将值添加到Set
     * @param key Redis键
     * @param value 值
     */
    public void addToSet(String key, Object value) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.add(key, value);
    }

    /**
     * 从Set中移除值
     * @param key Redis键
     * @param value 值
     */
    public void removeFromSet(String key, Object value) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.remove(key, value);
    }

    /**
     * 获取Set中的所有值
     * @param key Redis键
     * @return Set中的所有值
     */
    public Set<Object> getSetMembers(String key) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        return setOps.members(key);
    }

    /**
     * 检查Set中是否包含指定值
     * @param key Redis键
     * @param value 值
     * @return 是否包含
     */
    public boolean isSetMember(String key, Object value) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        return Boolean.TRUE.equals(setOps.isMember(key, value));
    }

    /**
     * 设置键的过期时间
     * @param key Redis键
     * @param timeout 过期时间
     * @param unit 时间单位
     */
    public void setExpire(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 检查键是否存在
     * @param key Redis键
     * @return 是否存在
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
} 